package com.tgy.admin.Service.impl;

import cn.dev33.satoken.secure.BCrypt;
import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.tgy.cache.AuthorInfo;
import com.tgy.constant.Constant;
import com.tgy.constant.RedisKey;
import com.tgy.core.repository.FriendLinkRepository;
import com.tgy.core.service.BlogUserService;
import com.tgy.mo.FriendLinkMO;
import com.tgy.pojo.BlogUser;
import com.tgy.util.RedisUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * 缓存数据
 * @author tianguiyin
 * @version 1.0
 * @date 2022/7/21 15:51
 */
@Component
public class CacheDataServiceImpl {

    final static Logger logger = LoggerFactory.getLogger(CacheDataServiceImpl.class);

    @Resource
    private RedisUtils redis;
    @Resource
    private FriendLinkRepository friendLinkRepository;
    @Resource
    private BlogUserService blogUserService;

    /**
     * 缓存友情链接数据
     */
    @PostConstruct
    public void cacheFriendLink(){
        try {
            // 查询出所有可用状态的友情链接
            List<FriendLinkMO> friendLinklist = friendLinkRepository.getAllByIsDelete(1);
            // 添加缓存
            redis.set(RedisKey.FRIEND_LINK, JSONObject.toJSONString(friendLinklist));
            logger.info("友情链接缓存成功");
        }catch (Exception e){
            logger.error("友情链接缓存失败"+e.getMessage());
        }

    }

    /**
     * 缓存作者信息数据
     */
    @PostConstruct
    public void cacheAuthorInfo(){
        try {
            if (!redis.keyIsExist(RedisKey.AUTHOR_INFO)){
                // 添加缓存
                AuthorInfo authorInfo = new AuthorInfo();
                redis.set(RedisKey.AUTHOR_INFO, JSONObject.toJSONString(authorInfo));
                // 添加数据库
                BlogUser blogUser = new BlogUser();
                BeanUtil.copyProperties(authorInfo,blogUser);
                initUser(blogUser);
                // 判断数据库是否有
                BlogUser user = blogUserService.queryById(blogUser.getId());
                if (Objects.isNull(user)){
                    blogUserService.insertByBo(blogUser);
                }else {
                    blogUserService.updateByBo(blogUser);
                }
                logger.info("作者信息初始化成功");
            }else {
                logger.info("作者信息缓存成功");
            }
        }catch (Exception e){
            logger.error("作者信息缓存失败"+e.getMessage());
        }

    }


    public static void initUser(BlogUser blogUser){
        blogUser.setStatus(Constant.AVAILABLE_TRUE);
        LocalDateTime now = LocalDateTime.now();
        blogUser.setCreatedTime(now);
        blogUser.setUpdatedTime(now);
        blogUser.setAddress(blogUser.getLatelyLoginAddress());
        blogUser.setPassword(BCrypt.hashpw(blogUser.getPassword()));
    }

}
